import { defineComponent, nextTick, ref, watch, watchEffect } from "vue";
import { useDraggable } from '@vueuse/core';
import styles from "./lPopup.module.less";
import { CloseOutlined, ShrinkOutlined, ArrowsAltOutlined, MinusOutlined } from '@ant-design/icons-vue';
import LIcon from "../lIcon/lIcon";
import { message } from "ant-design-vue";
import { useStore as useZIndexStore } from "./store/zIndex";
export default defineComponent({
  name: 'LPopup',
  props: {
    title: {
      type: String,
      default: '标题',
    },
    width: {
      type: String,
      default: '800px',
    },
    isFullScreen: {
      type: Boolean,
      default: false,
    },
  },
  emits: ([
    'beforeClose', //弹窗即将关闭时
    'closed', //弹窗关闭后
  ]),
  setup(props, { slots, expose, emit }) {
    const zIndexStore = useZIndexStore();
    // 层级
    let zIndex = ref(100);
    // 浮层打开状态
    const floatOpen = ref(false);
    // 卡片打开
    const cardShow = ref(false);
    // 打开弹窗
    const open = () => {
      if (cardShow.value) {
        return;
      }
      if (zIndex.value > 200) {
        message.error('打开的弹窗过多，请关闭部分弹窗重试!');
        return;
      }
      zIndex.value = zIndexStore.nextLPopupMax();
      floatOpen.value = true;
      cardShow.value = true;
    }
    // 关闭弹窗
    const close = () => {
      emit('beforeClose');
      nextTick(() => {
        cardShow.value = false;
        zIndexStore.preLPopupMax(zIndex.value);
        setTimeout(() => {
          floatOpen.value = false;
          isFullScreen.value = props.isFullScreen;
          isHidden.value = false;
          initDraggingState();
          emit('closed');
        }, 250);
      })
    }
    // 弹窗是否全屏
    const isFullScreen = ref(props.isFullScreen);
    // 弹窗是否缩起
    const isHidden = ref(false);
    expose({
      open,
      close,
      cardShow,
    })

    // 拖拽
    const popupTitleRef = ref(null as any);
    const { x, y, isDragging } = useDraggable(popupTitleRef);

    const startX = ref<number>(0);
    const startY = ref<number>(0);
    const startedDrag = ref(false);
    const transformX = ref(0);
    const transformY = ref(0);
    const preTransformX = ref(0);
    const preTransformY = ref(0);
    const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });
    const initDraggingState = () => {
      startX.value = 0;
      startY.value = 0;
      startedDrag.value = false;
      transformX.value = 0;
      transformY.value = 0;
      preTransformX.value = 0;
      preTransformY.value = 0;
      dragRect.value = { left: 0, right: 0, top: 0, bottom: 0 };
    }
    watch([x, y], () => {
      if (!startedDrag.value && !isFullScreen.value) {
        startX.value = x.value;
        startY.value = y.value;
        const bodyRect = document.body.getBoundingClientRect();
        const titleRect = popupTitleRef.value.getBoundingClientRect();
        dragRect.value.right = bodyRect.width - titleRect.width;
        dragRect.value.bottom = bodyRect.height - titleRect.height;
        preTransformX.value = transformX.value;
        preTransformY.value = transformY.value;
      }
      startedDrag.value = true;
    });
    watch(isDragging, () => {
      if (!isDragging) {
        startedDrag.value = false;
      }
    });

    watchEffect(() => {
      if (startedDrag.value) {
        transformX.value =
          preTransformX.value +
          Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) -
          startX.value;
        transformY.value =
          preTransformY.value +
          Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) -
          startY.value;
      }
    });

    // 弹窗卡片
    const PopupScreen = () => (
      <div
        class={[
          styles.PopupScreen,
          cardShow.value || styles.close,
          isFullScreen.value && styles.fullScreen,
          isHidden.value && styles.hidden
        ]}
        style={[
          { zIndex: zIndex.value },
          { transform: `translate(${transformX.value}px, ${transformY.value}px)` },
          `--popup-width: ${props.width}`
        ]}
        onClick={(e: any) => e.stopPropagation()}
      >
        <div
          ref={popupTitleRef}
          class={[styles.PopupScreenHeader, !isFullScreen.value && styles.canMove]}
        >
          <span class={styles.title}>{props.title}</span>
          <div class={styles.toolbar}>
            {
              isFullScreen.value || <div class={styles.icon} onClick={() => { isHidden.value = !isHidden.value; initDraggingState(); }}>
                {isHidden.value ? <LIcon type="icon-zhankai" /> : <MinusOutlined />}
              </div>
            }
            {
              isHidden.value || <div class={styles.icon} onClick={() => { isFullScreen.value = !isFullScreen.value; initDraggingState(); }}>
                {isFullScreen.value ? <ShrinkOutlined /> : <ArrowsAltOutlined />}
              </div>
            }
            <CloseOutlined class={styles.icon} onClick={() => { close() }} />
          </div>
        </div>
        {
          <div class={styles.popupContainer} style={{ display: isHidden.value ? 'none' : 'block' }}>
            {
              slots.default && slots.default()
            }
          </div>
        }
      </div>
    )
    const Components = () => (
      <>
        {
          floatOpen.value && <div>
            {
              <PopupScreen />
            }
          </div>
        }
      </>
    )
    return {
      Components
    }
  },
  render() {
    return <this.Components />
  },
})